import {
	TokenKey,
	LocalUserInfoKey,
	BaseUrl,
	ApiHost
} from '@/config/index.js'


import md5 from '@/utils/md5.js'
import store  from '@/store/index.js'

let task = {}



export default function({
	method = 'GET',
	data = {},
	param = {},
	header = {},
	url = '',
	auth = false,
	host = ApiHost,
	baseUrl = BaseUrl
}) {
	let api = host + baseUrl + url
	//格式化地址
	if (Object.keys(param).length > 0) {
		api += "?" + Object.keys(param).map(key => key + '=' + param[key]).join('&')
	}

	const token = uni.getStorageSync(TokenKey)
	if (auth && !token) {
		uni.showToast({
			icon: 'none',
			title: "请先登录"
		})
		uni.hideLoading()
		return Promise.reject('请先登录')
	}


	if (token) {
		header[TokenKey] = token
	}
	

	let startTime = new Date().getTime();
	return new Promise((resolve, reject) => {
		 uni.request({
			url: api,
			method,
			data,
			header,
			success(res) {
				
				let endTime = new Date().getTime();
				// if (url == '/market/market/getMarketList') {
				// 		console.time()
				// 		let ss=rasDecode(res.data,privateKey)
				// 		res.data={
				// 			code:1,
				// 			data:ss
				// 		}
				// 		console.timeEnd()
				// }
				uni.hideLoading()
				if (res.data.code == 1) {
					resolve(res.data)
				} else {
					switch (res.data.code) {
						case 400:
							store.dispatch('config/getConfig');
							uni.showToast({
								icon:'none',
								title:"配置有更新，请重试操作"
							})
							reject()
							break;
						case 401:
							setTimeout(() => {
								let routes = getCurrentPages();
								let curRoute = routes[routes.length - 1].route
								if (curRoute == 'pages/login/login') return;
								store.dispatch('user/logout');
							}, 1500)
							break;
						case 710:
							uni.showModal({
								content: "您还未开户，是否立即开户？",
								success({
									confirm
								}) {
									if (confirm) {
										uni.navigateTo({
											url: '/pages/wallet/wallet'
										})
									}
								}
							})
							break;
						case 702:
							uni.showModal({
								content: "您还未实名，是否去实名认证？",
								success({
									confirm
								}) {
									if (confirm) {
										uni.navigateTo({
											url: '/pages/certification/certification'
										})
									}
								}
							})
							break;
						case 801:
							store.dispatch('config/targetExchange',true)
							reject(res.data);
						case 4003:
						case 777:
						case 3003:
							reject(res.data)
							// 这里不提示
							break;
						default:
							uni.showToast({
								title: res.data.msg || "服务繁忙",
								icon: "none"
							})
							reject(res.data)
					}

				}
			},
			fail(err) {
				if (!err.errMsg.includes('abort')) {
					uni.hideLoading()
					uni.showToast({
						title: err.errMsg || "服务繁忙",
						icon: "error"
					})
				}
			}
		})
	})


}



